package logic.weapons.projectileWeapons.heatSeeker;

import com.jme.math.Quaternion;
import com.jme.math.Vector3f;
import com.jme.scene.Spatial;

import logic.nodes.damagable.DamagableNode;
import logic.ships.Ship;
import logic.ships.hunter.Hunter;
import logic.weapons.WeaponFireController;

public class HeatSeekerController extends WeaponFireController {
	
	private static final long serialVersionUID = 1L;
	
	private Spatial target;
	private HeatSeeker heatSeeker;
	
	public HeatSeekerController(HeatSeeker heatSeeker, Ship ship, Vector3f dir) {
		super(heatSeeker, ship, dir);
		target = heatSeeker.getTarget();
		this.heatSeeker = heatSeeker;
	}
	
	public void changeTarget(Spatial newTarget) { target = newTarget; }
	
	@Override
	public void update(float time) {
		if(target != null) {
			if(target instanceof DamagableNode 
			&& ((DamagableNode)target).isDestroyed()) {
				if(target instanceof Hunter) ((Hunter)target).removeHeatSeeker(heatSeeker);
				super.update(time);
				return;
			}
			
			Vector3f targetPos = target.getLocalTranslation();
			
			Quaternion oldRot = new Quaternion(heatSeeker.getLocalRotation());
			heatSeeker.lookAt(targetPos, Vector3f.UNIT_Y);
			Quaternion targetRot = new Quaternion(heatSeeker.getLocalRotation());
			
			heatSeeker.getLocalRotation().set(oldRot);
			heatSeeker.getLocalRotation().slerp(targetRot, time * heatSeeker.getAgility());
		}
		super.update(time);
	}
}